package com.ricky.net;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.ricky.core.net.ClientServer;
import com.ricky.core.net.abs.Request;
import com.ricky.core.net.abs.NetServer;
import com.ricky.core.net.i.IMessageListener;
import com.ricky.core.net.i.IServerListener;
import com.ricky.core.net.msg.Context;
import com.ricky.job.MsgTask;

/***
 *	Connector.java</br>
 *	@author pu
 *  @Data 2011-11-1</br>
 *	@version v0.1</br>
 *	@Discription 链接服务
 ***/
public class Connector implements IMessageListener<Context<?>>,IServerListener {
	
	protected static Logger log = Logger.getLogger(Connector.class);

	/**
	 * 连接器
	 */
	public NetServer connServer;

	/**
	 * 消息处理器
	 */
	public ExecutorService workQueue;
	
	private String host;
	
	private int port;

	/**
	 * 在初始化之前调用
	 * @param host
	 * @param port
	 */
	public void connect(String host,int port)
	{
		this.host=host;
		this.port=port;
	}
	
	public Connector(String host,int port)
	{
		this.host=host;
		this.port=port;
	}
	
	/**
	 * 初始化
	 */
	public void init() {

		int nThreads = Runtime.getRuntime().availableProcessors() * 2;
		if (nThreads < 4) {
			nThreads = 4;
		}
		
		workQueue =Executors.newSingleThreadExecutor();// 

		connServer =new  ClientServer(host, port);
		connServer.setIserverListener(this);
		connServer.setIMessageListener(this);
		connServer.init();
	}

	/**
	 * 启动
	 */
	public void start() {
		connServer.start();
		log.info("连接服务已启动，目标主机" + host + "：" + port);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onMessageArrived(com.ricky.core
	 * .net.Context)
	 */
	@Override
	public void onMessageArrived(Request request,Context<?> context) {
		workQueue.submit(new MsgTask(request,(Context<Map<String, Object>>) context.getContent()));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onConnectionOpend(com.ricky.core
	 * .net.abs.NetConnection)
	 */
	@Override
	public void onConnectionOpend(Request conn) {
		log.info("链接打开！。");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onConnectionClosed(com.ricky.
	 * gmAgent.net.abs.NetConnection)
	 */
	@Override
	public void onConnectionClosed(Request conn) {
		// TODO Auto-generated method stub
		log.info("链接关闭！。");

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onConnectionCreated(com.ricky
	 * .gmAgent.net.abs.NetConnection)
	 */
	@Override
	public void onConnectionCreated(Request conn) {
		// TODO Auto-generated method stub
		log.info("链接创建！。");
	}

}
